<?php
require '../db.php';
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$settings = file_exists(__DIR__ . '/../settings.json') ? json_decode(file_get_contents(__DIR__ . '/../settings.json'), true) : ['title' => '游侠网盘'];
$site_title = $settings['title'];

// 总上传文件数
$file_count_stmt = $conn->query("SELECT COUNT(*) as total_files FROM files");
$total_files = $file_count_stmt->fetch_assoc()['total_files'];

// 累计存储空间（动态单位）
$total_size = 0;
$size_stmt = $conn->query("SELECT path FROM files");
while ($file = $size_stmt->fetch_assoc()) {
    if (file_exists($file['path'])) {
        $total_size += filesize($file['path']);
    }
}
// 动态选择单位
if ($total_size >= 1024 * 1024 * 1024) { // GB
    $total_size_display = round($total_size / (1024 * 1024 * 1024), 2) . ' GB';
} elseif ($total_size >= 1024 * 1024) { // MB
    $total_size_display = round($total_size / (1024 * 1024), 2) . ' MB';
} elseif ($total_size >= 1024) { // KB
    $total_size_display = round($total_size / 1024, 2) . ' KB';
} else { // Bytes
    $total_size_display = $total_size . ' Bytes';
}

// 用户总数
$user_count_stmt = $conn->query("SELECT COUNT(*) as total_users FROM users");
$total_users = $user_count_stmt->fetch_assoc()['total_users'];

// 服务器信息
$os = php_uname('s') . ' ' . php_uname('r');
$php_version = phpversion();
$server_ip = gethostbyname(gethostname());
$memory_usage = round(memory_get_usage() / (1024 * 1024), 2);
$disk_total = disk_total_space(__DIR__);
$disk_free = disk_free_space(__DIR__);
$disk_used = $disk_total - $disk_free;
$disk_total_gb = round($disk_total / (1024 * 1024 * 1024), 2);
$disk_used_gb = round($disk_used / (1024 * 1024 * 1024), 2);
$disk_free_gb = round($disk_free / (1024 * 1024 * 1024), 2);

// 最近上传文件（前 5 个）
$recent_files_stmt = $conn->prepare("SELECT f.name, f.upload_time, u.username 
                                     FROM files f 
                                     JOIN users u ON f.user_id = u.id 
                                     ORDER BY f.upload_time DESC 
                                     LIMIT 5");
$recent_files_stmt->execute();
$recent_files = $recent_files_stmt->get_result();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理 - <?= htmlspecialchars($site_title) ?></title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="<?= $settings['theme'] === 'dark' ? 'bg-dark text-white' : '' ?>">
    <nav class="navbar navbar-expand-lg <?= $settings['theme'] === 'dark' ? 'navbar-dark bg-dark' : 'navbar-light bg-light' ?>">
        <div class="container">
            <a class="navbar-brand" href="index.php">后台管理</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="../index.php">网站前台</a></li>
                    <li class="nav-item"><a class="nav-link" href="users.php">用户管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="files.php">文件管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="categories.php">分类管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="settings.php">网站设置</a></li>
                    <li class="nav-item"><a class="nav-link" href="../logout.php">退出</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container py-5">
        <h2>管理中心</h2>

        <!-- 统计信息 -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="card text-center">
                    <div class="card-body">
                        <h5 class="card-title">总上传文件数</h5>
                        <p class="card-text"><span class="text-danger fw-bold"><?= $total_files ?></span> 个</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card text-center">
                    <div class="card-body">
                        <h5 class="card-title">文件总存储空间</h5>
                        <p class="card-text"><span class="text-danger fw-bold"><?= $total_size_display ?></span></p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card text-center">
                    <div class="card-body">
                        <h5 class="card-title">总用户数</h5>
                        <p class="card-text"><span class="text-danger fw-bold"><?= $total_users ?></span> 个</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 服务器信息 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5>服务器信息</h5>
            </div>
            <div class="card-body">
                <ul class="list-group list-group-flush">
                    <li class="list-group-item">操作系统：<?= $os ?></li>
                    <li class="list-group-item">PHP 版本：<?= $php_version ?></li>
                    <li class="list-group-item">服务器 IP：<?= $server_ip ?></li>
                    <li class="list-group-item">当前内存使用：<?= $memory_usage ?> MB</li>
                    <li class="list-group-item">磁盘总空间：<?= $disk_total_gb ?> GB</li>
                    <li class="list-group-item">磁盘已用空间：<?= $disk_used_gb ?> GB</li>
                    <li class="list-group-item">磁盘剩余空间：<?= $disk_free_gb ?> GB</li>
                </ul>
            </div>
        </div>

        <!-- 最近上传文件 -->
        <div class="card">
            <div class="card-header">
                <h5>最近上传文件</h5>
            </div>
            <div class="card-body">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>文件名</th>
                            <th>上传时间</th>
                            <th>上传者</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($file = $recent_files->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($file['name']) ?></td>
                                <td><?= $file['upload_time'] ?></td>
                                <td><?= htmlspecialchars($file['username']) ?></td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>